(function (window, angular) {
  "use strict";
  angular
    .module("Controller.Maintenance.Vehicle", [])
    .controller("VehicleCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", "$state", function ($scope, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService, $state) {
        $scope.activeFlag = [true, false, false, false, false];
        $scope.markInfo = {
          allChecked: false,
        };
        $scope.pageInfo = {
          totalPages: 1,
          totalRows: 0,
          pageSize: 10,
          curPage: 1,
        };
        $scope.toolbarConfig = {
          showAdvanceSearch: false,
          showColConfig: false,
        };

        $scope.dataList = [];
        $scope.condition = {};

        $scope.detailInfo = {};

        $scope.tbConf = {
          fixedWidth: 170,
          scrollWidth: 1000,
          tableCol: [
            {
              name: "当前服务商",
              width: 180,
              dataField: "currentAgentName",
              isShow: true,
              isFixed: false,
            },
            {
              name: "产品型号",
              width: 120,
              dataField: "productModel",
              isShow: true,
              isFixed: false,
            },
            {
              name: "整车编码",
              width: 160,
              dataField: "vehicleNo",
              isShow: true,
              isFixed: false,
              clickFn: "viewDetail",
            },
            {
              name: "购机日期",
              width: 140,
              dataField: "purchaseDateShow",
              isShow: true,
              isFixed: false,
            },
            {
              name: "出保日期",
              dataField: "warrantyReleaseDateShow",
              width: 140,
              isShow: true,
              isFixed: false,
            },
            {
              name: "顾客单位",
              width: 100,
              dataField: "tenantName",
              isShow: true,
              isFixed: false,
            },
            {
              name: "所属代理商",
              width: 180,
              dataField: "belongAgentName",
              isShow: true,
              isFixed: false,
            },
            {
              name: "操作",
              isShow: true,
              isFixed: true,
            },
          ],
        };

        $scope.setFixedWidth = function () {
          $scope.tbStyle = {
            scrollLeft: {
              left: $scope.tbConf.fixedWidth + "px",
            },
          };
        };

        $scope.exportParam = {
          sectionUrl: ybHttp.RequestUrl("mt", "/productArchive/export"),
          sectionParam: {ids: []},
          allUrl: ybHttp.RequestUrl("mt", "/productArchive/exportAll")
        };

        $scope.changeTab = function (index) {
          $scope.activeFlag = [false, false, false, false, false, false];
          $scope.activeFlag[index] = true;
          switch (index) {
            case 0:
              initData();
              break;
            default:
              break;
          }
        };

        function initData() {
          $scope.detailInfo = {};
        }

        $scope.search = function (curpage) {
          getDataList(curpage);
        };

        $scope.reset = function () {
          $scope.condition = {};
        };

        $scope.viewImage = function (item) {
          ybWidget.ViewImage({
            FileUrl: item,
          });
        };

        function getDataList(curPage) {
          var service = "mt";
          var reqUrl = "/productArchive/list";
          var param = {};
          if (!!curPage) {
            $scope.pageInfo.curPage = curPage;
          }
          param.pageSize = $scope.pageInfo.pageSize;
          param.pageNum = $scope.pageInfo.curPage;
          param.filters = $scope.condition;
          ybHttp.Post(service, reqUrl, param).then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            $scope.markInfo.allChecked = false;
            angular.forEach(resp.value.list, function (item) {
              item.isChecked = false;
              item.purchaseDateShow = $filter("YbDate")(item.purchaseDate, "yyyy-MM-dd HH:mm:ss");
              item.warrantyReleaseDateShow = $filter("YbDate")(item.warrantyReleaseDate, "yyyy-MM-dd HH:mm:ss");
            });
            $scope.pageInfo.totalRows = resp.value.total;
            $scope.pageInfo.totalPages = resp.value.pages;
            $scope.dataList = resp.value.list;
          });
        }

        $scope.switchToolbar = function (toolbar) {
          if (!!$scope.toolbarConfig["show" + toolbar]) {
            $scope.toolbarConfig["show" + toolbar] = false;
          } else {
            $timeout(function () {
              $scope.toolbarConfig["show" + toolbar] = true;
            });
          }
        };

        $scope.selectRow = function (index) {
          $scope.markInfo.curRow = index;
        };

        function checkAll() {
          var selectAllFlag = false;
          for (var i = 0, len = $scope.dataList.length; i < len; i++) {
            if (!$scope.dataList[i].isChecked) {
              selectAllFlag = false;
              break;
            }
            selectAllFlag = true;
          }
          return selectAllFlag;
        }

        $scope.selectSingle = function (item) {
          if (!item.isChecked) {
            $scope.markInfo.allChecked = false;
          } else {
            $scope.markInfo.allChecked = checkAll();
          }
          getBillIds();
        };

        $scope.selectAll = function () {
          for (var i = 0, len = $scope.dataList.length; i < len; i++) {
            $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
          }
          getBillIds();
        };

        function getBillIds() {
          $scope.exportParam.sectionParam.ids = [];
          angular.forEach($scope.dataList, function (item) {
            if (!!item.isChecked) {
              $scope.exportParam.sectionParam.ids.push(item.id);
            }
          });
        }

        $scope.viewDetail = function(item) {
          $scope.detailInfo = JSON.parse(JSON.stringify(item));
          $scope.changeTab(2);
        };

        $scope.editData = function (item) {
          $scope.detailInfo = JSON.parse(JSON.stringify(item));
          $scope.changeTab(1);
        };

        $scope.saveData = function () {
          var service = "mt";
          var reqUrl = "/productArchive/update";

          ybHttp.Post(service, reqUrl, $scope.detailInfo).then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            ybWidget.ShowToaster("success", "操作成功");
            $scope.changeTab(0);
            getDataList();
          });
        };

        $scope.selectAgent = function () {
          const options = {
            title: '业务伙伴',
            service: 'device',
            url: '/companyDealer/listTejiWeixiu',
            otherParams: { dealerTypeList: [5] },
            keyWords: [{ label: '客户编号', field: 'dealerCode' }, { label: '客户名称', field: 'companyName' }],
            fields: [
              {
                name: '客户编号',
                dataField: 'dealerCode',
                width: "40%"
              },
              {
                name: '客户名称',
                dataField: 'companyName',
                width: "60%"
              }
            ]
          }
          ybWidget.DataSelector(options).then(function (data) {
            $scope.detailInfo.currentAgent = data.dealerOrgId;
            $scope.detailInfo.currentAgentName = data.companyName;
          })
        };

        $scope.clearAgent = function () {
          $scope.detailInfo.currentAgent = '';
          $scope.detailInfo.currentAgentName = '';
        };

        $scope.viewRepair = function (val) {
          $state.go("app.maintenance.repair", { engineNo: val })
        };

        $scope.importGuaranteePeriodAndHours = function () {
          var param = {
              name: "三包期限和三包小时",
              templateReqService: "mt",
              templateReqUrl: "/productArchive/downloadSanbaoInfoTemp",
              importReqService: "mt",
              importReqUrl: "/productArchive/importSanbaoInfo",
              importErrorUrl: ""
          };
          ybWidget.ImportFile(param).then(function (data) {
              getDataList(1);
          });
        };

        $scope.viewGss = function(val) {
          window.open(`https://xgss.xcmg.com/mobile/#/pin/${val}/384`)
        };

        $scope.checkDate = function (obj, startFiled, endFiled) {
          var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
          if (!!timeFormatObj.tStart) {
              obj[startFiled] = timeFormatObj.tStart;
          }
          if (!!timeFormatObj.tEnd) {
              obj[endFiled] = timeFormatObj.tEnd;
          }
        };

        var btnPermissionCode = {
          VEHICLE_EDIT: window.ActionCode.VEHICLE_EDIT,
          VEHICLE_PASS: window.ActionCode.VEHICLE_PASS,
          VEHICLE_REJECT: window.ActionCode.VEHICLE_REJECT,
          VEHICLE_DELETE: window.ActionCode.VEHICLE_DELETE,
        };

        $scope.btnPermission = {
          VEHICLE_EDIT: true,
          VEHICLE_PASS: true,
          VEHICLE_REJECT: true,
          VEHICLE_DELETE: true,
        };

        function setBtnPermission() {
          for (var key in btnPermissionCode) {
            $scope.btnPermission[key] = UserContextService.CheckPermission([
              btnPermissionCode[key],
            ]);
          }
        }

        (function () {
          if ($scope.isFWZ) {
            $scope.tbConf.tableCol = ybWidget.HideTableCols($scope.tbConf.tableCol, ['belongAgentName']);
          }

          UserContextService.SetBtnPermission(setBtnPermission);
          getDataList();
          $scope.setFixedWidth();
        })();
      },
    ]);
})(window, window.angular);
